package com.travelsky.airchina.boarding.web.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.travelsky.airchina.boarding.domain.Role;
import com.travelsky.airchina.boarding.domain.User;
import com.travelsky.airchina.boarding.service.RoleService;
import com.travelsky.airchina.boarding.service.UserService;
import com.travelsky.airchina.boarding.web.ResourceNotFoundException;
import com.travelsky.airchina.boarding.web.validator.UserValidator;

@Controller
@RequestMapping(value="/system/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	/**
	 * 角色用户列表首页
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/manage", method=RequestMethod.GET)
	public String manage(Model model) {
		List<User> list = userService.findAllUser();
		model.addAttribute("list",list);
		return "system/user/userList";
	}
	/**
	 * 转到创建用户页面
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String toCreate(Model model) {
		model.addAttribute(new User());
		List<Role> roleList = roleService.findAllRoles("1");
		model.addAttribute("roleList", roleList!=null?roleList:new ArrayList<Role>());
		return "system/user/createForm";
	}
	/**
	 * 创建用户
	 * @param user
	 * @param result
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public String create(@ModelAttribute("user") User user, BindingResult result,Model model,HttpServletRequest request) {
		String roleId = request.getParameter("roleId");
		if(roleId!=null && !"".equals(roleId)){
			Role role = new Role();
			role.setId(new Long(roleId));
			user.setRole(role);
		}
		String confirmPassword = request.getParameter("confirmLoginPassword");
		new UserValidator().validate(user,userService,confirmPassword,result);
		if (result.hasErrors()) {
			List<Role> roleList = roleService.findAllRoles("1");
			model.addAttribute("roleList", roleList!=null?roleList:new ArrayList<Role>());
			return "system/user/createForm";
		}
		Date createdTime = new Date();
		user.setCreatedTime(createdTime);
		user.setLastUpdatedTime(createdTime);
		userService.saveOrUpdateUser(user);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/user/" + user.getId();
	}
	/**
	 * 转到修改用户页面
	 * @param id 角色的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String toUpdate(@PathVariable Long id, Model model) {
		List<Role> roleList = roleService.findAllRoles("1");
		model.addAttribute("roleList", roleList!=null?roleList:new ArrayList<Role>());
		User user = this.userService.getUser(id);
		if (user == null) {
			throw new ResourceNotFoundException(id);
		}
		model.addAttribute(user);
		return "system/user/updateForm";
	}
	/**
	 * 转到修改角色页面
	 * @param id 角色的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(@ModelAttribute User user, BindingResult result,Model model,HttpServletRequest request) {
		String roleId = request.getParameter("roleId");
		if(roleId!=null && !"".equals(roleId)){
			Role role = new Role();
			role.setId(new Long(roleId));
			user.setRole(role);
		}
		String confirmPassword = request.getParameter("confirmLoginPassword");
		new UserValidator().validate(user,userService,confirmPassword,result);
		if (result.hasErrors()) {
			List<Role> roleList = roleService.findAllRoles("1");
			model.addAttribute("roleList", roleList!=null?roleList:new ArrayList<Role>());
			return "system/user/updateForm";
		}
		Date createdTime = new Date();
		user.setCreatedTime(createdTime);
		user.setLastUpdatedTime(createdTime);
		userService.saveOrUpdateUser(user);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/user/"+user.getId();
	}
	/**
	 * 查看用户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="{id}", method=RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model,HttpServletRequest request) {
		List<Role> roleList = roleService.findAllRoles("1");
		model.addAttribute("roleList", roleList!=null?roleList:new ArrayList<Role>());
		User user = this.userService.getUser(id);
		if (user == null) {
			throw new ResourceNotFoundException(id);
		}
		model.addAttribute(user);
		setRequestOperationFlag(request);
		return "system/user/view";
	}
	/**
	 * 操作后设置操作成功或失败的标志
	 * @param request
	 * @param operationFlag
	 */
	private void setSessionOperationFlag(HttpServletRequest request,String operationFlag){
		request.getSession().setAttribute("operationFlag", operationFlag);
	}
	/**
	 * 从session中取得操作成功或失败的标志,并设置在request
	 * @param request
	 */
	private void setRequestOperationFlag(HttpServletRequest request){
		HttpSession session = request.getSession();
		String operationFlag = (String)session.getAttribute("operationFlag");
		if(operationFlag!=null){
			request.setAttribute("operationFlag", operationFlag);
			session.removeAttribute("operationFlag");
		}
	}
	/**
	 * 通过ajax用户名是否已经使用
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/checkLoginName", method=RequestMethod.GET)
	public @ResponseBody boolean checkLoginName(@RequestParam String loginName,@RequestParam String oldLoginName) {
		if(oldLoginName!=null && !"".equals(loginName)){
			if(!oldLoginName.equals(loginName) && userService.validateUserLoginNameExist(loginName)){
				return false;
			}
		}else{
			if(userService.validateUserLoginNameExist(loginName)){
				return false;
			}
		}
		return true;
	}
}
